﻿using MyDapperApi.Services;
using Newtonsoft.Json;
using System;
using System.Diagnostics;
using System.Reflection;
using System.Threading.Tasks;

namespace QYWXUpdate.DataModel
{
    /// <summary>
    /// 标准返回参数
    /// </summary>
    public class CommonResponse
    {
        public int code { get; set; }
        public string msg { get; set; }
        public bool Success { get; set; }
        public object data { get; set; }
        private readonly DateBaseService _dateBaseService;
        // 标记当前类的核心方法（SetSuccess/SetError），用于定位调用链
        private readonly string[] _targetEntryMethods = { "SetSuccess", "SetError" };

        // 构造函数保持不变
        public CommonResponse()
        {
            _dateBaseService = CreateDateBaseService();
        }

        public CommonResponse(DateBaseService dateBaseService)
        {
            _dateBaseService = dateBaseService;
        }

        private DateBaseService CreateDateBaseService()
        {
            var configuration = new ConfigurationBuilder()
                .AddJsonFile("appsettings.json")
                .Build();

            return new DateBaseService(configuration);
        }

        /// <summary>
        /// 设置操作成功的结果信息
        /// </summary>
        public void SetSuccess(object obj = null, bool log = false)
        {
            code = 200;
            msg = "ok";
            Success = true;
            this.data = obj;

            if (log)
            {
                LogMethodCall(1, obj).ConfigureAwait(false);
            }
        }

        public void SetSuccess() => SetSuccess(null);

        public void SetError(string data)
        {
            code = 100;
            msg = "false";
            Success = false;
            this.data = data;

            LogMethodCall(2, data).ConfigureAwait(false);
        }

        public void SetError() => SetError(null);

        // 日志核心方法 - 精准定位业务调用方法
        private async Task LogMethodCall(int type, object obj)
        {
            try
            {
                var stackTrace = new StackTrace(true); // 启用栈帧详情
                MethodBase businessMethod = null;

                // 第一步：遍历栈帧，找到 SetSuccess/SetError 方法在栈中的位置
                for (int i = 0; i < stackTrace.FrameCount; i++)
                {
                    var frame = stackTrace.GetFrame(i);
                    var method = frame?.GetMethod();
                    if (method == null) continue;

                    // 找到 SetSuccess 或 SetError 方法
                    if (_targetEntryMethods.Contains(method.Name) &&
                        method.DeclaringType == _currentType)
                    {
                        // 第二步：取它的上一层栈帧（i+1），就是调用它的业务方法
                        var businessFrame = stackTrace.GetFrame(i + 1);
                        if (businessFrame != null)
                        {
                            businessMethod = businessFrame.GetMethod();
                        }
                        break; // 找到目标后立即退出，避免无效遍历
                    }
                }

                // 处理找到的业务方法
                if (businessMethod != null && businessMethod.DeclaringType != null)
                {
                    string methodName = businessMethod.Name;
                    string className = businessMethod.DeclaringType.Name;
                    // 处理嵌套类（如 "QueueService+InnerClass" → "QueueService"）
                    if (className.Contains("+"))
                    {
                        className = className.Split('+')[0];
                    }

                    // 序列化数据
                    string objJson = "null";
                    if (obj != null)
                    {
                        try
                        {
                            objJson = JsonConvert.SerializeObject(obj);
                        }
                        catch (Exception ex)
                        {
                            objJson = $"序列化失败: {ex.Message}";
                        }
                    }

                    // 构建日志
                    string logMessage = type == 1
                        ? $"方法 {className}.{methodName} 调用了SetSuccess，数据：{objJson}"
                        : $"方法 {className}.{methodName} 调用了SetError，数据：{objJson}";

                    // 输出+存库
                    Console.WriteLine($"[{DateTime.Now:yyyy-MM-dd HH:mm:ss}] {logMessage}");
                    if (_dateBaseService != null && objJson != null)
                    {
                        _dateBaseService.CreateLog(methodName, className, objJson, type);
                    }
                }
                else
                {
                    // 调试辅助：输出完整栈帧，帮你分析结构
                    Console.WriteLine("未找到业务调用方法，完整调用栈：");
                    _dateBaseService.CreateLog("手动", "TTT", obj.ToString(), type);
                    for (int i = 0; i < stackTrace.FrameCount; i++)
                    {
                        var frame = stackTrace.GetFrame(i);
                        var method = frame?.GetMethod();
                        string methodInfo = method == null
                            ? "未知方法"
                            : $"{method.DeclaringType?.Name}.{method.Name}";
                        Console.WriteLine($"栈帧[{i}]: {methodInfo}");
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"日志记录失败: {ex.Message}");
            }
        }

        // 当前类类型（简化代码）
        private Type _currentType => typeof(CommonResponse);
    }
}